package cn.edu.flink.tutorial.processFunction;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.*;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import cn.edu.flink.tutorial.source.UDSourceFunction;

public class KeyedProcessFunction {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<Long> streamSource = env.addSource(new UDSourceFunction());

        DataStream<Tuple2<Long, Long>> mapedOutput = streamSource.map(
                new MapFunction<Long, Tuple2<Long, Long>>() {
                    @Override
                    public Tuple2<Long, Long> map(Long l) throws Exception {
                        return Tuple2.of(l, 1L);
                    }
                });

        KeyedStream<Tuple2<Long, Long>, Tuple> keyedOutput = mapedOutput.keyBy(0);
        DataStream<String> processedOutput = keyedOutput.process(
                new ProcessFunction<Tuple2<Long, Long>, String>() {
                    @Override
                    public void processElement(Tuple2<Long, Long> integerIntegerTuple2, ProcessFunction<Tuple2<Long, Long>, String>.Context context, Collector<String> collector) throws Exception {
                        collector.collect(integerIntegerTuple2.toString());
                    }
                }
        );

        processedOutput.print();

        env.execute();
    }
}
